# coding: utf8


def test_shortstr_smallint_resident():
    # short string
    # large string may always same object, if the two strings are created by multiply short string with constant integer
    # but will get different objects if multiply short string by integer var
    xs1 = 'a_123'*820
    xs2 = 'a_123'*820
    ss1 = 'abc123'*682
    ss2 = 'abc123'*682
    ls1 = 'abc123'*683      # this is minimum integer to get different object
    ls2 = 'abc123'*683      # resident string length is 4096!
    vi = 2
    vs1 = 'abc123'*vi
    vs2 = 'abc123'*vi
    v0 = 0
    vs01 = 'abc123'*v0
    vs02 = 'abc123'*v0
    v1 = 1
    vs11 = 'abc123'*v1
    vs12 = 'abc123'*v1
    print(
        f"# Python支撑编译期确定的字符串常驻内存，"
        f"# 所以，字符串乘以常数形成的短字符串可以驻留:\n"
        f" >>> ss1 = 'abc123'*{int(len(ss1)/6)}\n"
        f" >>> ss2 = 'abc123'*{int(len(ss2)/6)}\n"
        f" >>> print('id(ss1)=', id(ss1), 'id(ss2)=', id(ss2))\n"
        f"id(ss1)={id(ss1)}, id(ss2)={id(ss2)}\n"
        f" >>> xs1 = 'a_123'*{int(len(xs1)/5)}\n"
        f" >>> xs2 = 'a_123'*{int(len(xs2)/5)}\n"
        f" >>> print('id(xs1)=', id(xs1), 'id(xs2)=', id(xs2))\n"
        f"id(xs1)={id(xs1)}, id(xs2)={id(xs2)}\n"
        f"\n"
        f"# 经过测试，长度超过4096的字符串，不能驻留:\n"
        f" >>> s1 = 'abc123'*{int(len(ls1)/6)}      # 长度超过4096, 赋值后会产生不同的字符串对象\n"
        f" >>> s2 = 'abc123'*{int(len(ls2)/6)}\n"
        f" >>> print('id(ls1)==id(ls2):', id(ls1)==id(ls2),  id(ls1), id(ls2))\n"
        f"id(ls1)==id(ls2): {id(ls1)==id(ls2)},  {id(ls1)}, {id(ls2)}\n"
        f"\n"
        f"# Python不支持运行时判断字符串驻留，使用变量乘以字符串时，除了0和1之外，都不会驻留:\n"
        f" >>> v0， v1 = 0, 1\n"
        f" >>> vs01 = 'abc123'*v0                   # 任何字符串乘以0产生空串，驻留内存\n"
        f" >>> vs02 = 'abc123'*v0\n"
        f" >>> print('id(vs01)=', id(vs01), 'id(vs02)=', id(vs02))\n"
        f"id(vs01)={id(vs01)}, id(vs02)={id(vs02)}\n"
        f" >>> vs11 = 'abc123'*v1                   # 字符串乘以1，不改变原串，驻留内存\n"
        f" >>> vs12 = 'abc123'*v1\n"
        f" >>> print('id(vs11)=', id(vs11), 'id(vs12)=', id(vs12))\n"
        f"id(vs11)={id(vs11)}, id(vs12)={id(vs12)}\n"
        f" >>> vi = {vi}                            # 变量值大于等于2时，产生的字符串不驻留内存\n"
        f" >>> vs1 = 'abc123'*vi\n"
        f" >>> vs2 = 'abc123'*vi\n"
        f" >>> print('id(vs1)=', id(vs1), 'id(vs2)=', id(vs2))\n"
        f"id(vs1)={id(vs1)}, id(vs2)={id(vs2)}\n"
    )

    # for i in range(10, 10000):
    #     s1 = '123_abc'*i
    #     s2 = '123_abc'*i
    #     if id(s1) != id(s2):
    #         print(
    #             f" >>> s1 = '123_abc'*{i}\n"
    #             f" >>> s2 = '123_abc'*{i}\n"
    #             f"{id(s1), id(s2)}\n"
    #         )
    #         break
